import traceback
from urllib.request import Request
from starlette.responses import JSONResponse
from .exception import ResponseExceptionEnum
from .middleware import request_id_context
from loguru import logger


async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理
       后续还可以针对自定义的exception进行处理
    """
    # 从上下文变量获取请求 ID
    request_id = request_id_context.get("request_id")

    # 记录错误信息
    exception_detail = f"Request failed: {exc} {traceback.format_exc()}"
    #  绑定 request_id，记录错误信息
    logger_with_context = logger.bind(request_id=request_id)
    logger_with_context.error(exception_detail)

    return JSONResponse(
        status_code=500,  # http 状态码
        content={
            "code": ResponseExceptionEnum.SYSTEM_ERROR,  # 自定义错误码
            "message": str(exc),
            "data": None,
            "request_id": request_id,
        }
    )